package com.dxy.shardingjdbc.controller;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.shardingjdbc.keygenerator.MyShardingKeyGenerator;
import com.dxy.shardingjdbc.model.po.Alarm;
import com.dxy.shardingjdbc.service.AlarmService;
import com.dxy.shardingjdbc.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;

/**
 * 报警表(Alarm)表控制层
 *
 * @author dangxianyue
 * @since 2023-02-03 13:52:21
 */
@Api(tags = "告警接口")
@RestController
@RequestMapping("alarm")
public class AlarmController {

    @Resource
    private AlarmService alarmService;

    @ApiOperation("测试自定义id生成器")
    @GetMapping("/testMyShardingKeyGenerator")
    public String testMyShardingKeyGenerator() {
        int count = 0;
        MyShardingKeyGenerator generator = new MyShardingKeyGenerator();
        HashSet<String> set = new HashSet<>();
        long start = System.currentTimeMillis();
        // 统计1分钟能产生多少个id
        do {
            Long id = (Long) generator.generateKey();
            count++;
            System.out.println(id);
            set.add(id + "");
        } while (System.currentTimeMillis() <= start + 60 * 1000);
        System.out.println("count: " + count);//8239
        System.out.println("keys: " + set.size());//8239
        //按9000算，大约每秒钟产生150个id
        return "OK";
    }

    @ApiOperation("新增告警")
    @PostMapping("/save")
    public Alarm save(String alarmContent, String alarmTimeStr, Long companyId) {
        LocalDateTime alarmTime = LocalDateTimeUtil.parse(alarmTimeStr, "yyyy-MM-dd HH:mm:ss");
        System.out.println("alarmTime: " + alarmTime);

        //id的生成规则是以6位日期 yyMMdd 开始，如：230208xxx
        String alarmId = LocalDateTimeUtil.format(alarmTime,"yyMMdd")
                + String.format("%08d",RedisUtil.incrBy("alarm-id",1));

        Alarm alarm = new Alarm()
                .setId(Long.parseLong(alarmId))
                .setAlarmContent(alarmContent)
                .setAlarmTime(alarmTime)
                .setCompanyId(companyId);
        alarmService.save(alarm);
        return alarm;
    }

    @ApiOperation("根据id查找")
    @GetMapping("/findById/{id}")
    public Alarm findById(@PathVariable("id") Long id) {
        return alarmService.getById(id);
    }

    /*
     * 没有配置alarmTime范围分片策略的话，会去所以节点中查找，然后再汇总返回
     * 分页查询怎么办？做映射表？放到Redis？放到ElasticSearch？
     */
    @ApiOperation("根据alarmTime查找")
    @GetMapping("/findByAlarmTime")
    public List<Alarm> findByAlarmTime(String alarmTimeStart, String alarmTimeEnd) {
        return alarmService.list(new LambdaQueryWrapper<Alarm>()
                .ge(StringUtils.isNotBlank(alarmTimeStart), Alarm::getAlarmTime, LocalDateTimeUtil.parse(alarmTimeStart, "yyyy-MM-dd HH:mm:ss"))
                .le(StringUtils.isNotBlank(alarmTimeEnd), Alarm::getAlarmTime, LocalDateTimeUtil.parse(alarmTimeEnd, "yyyy-MM-dd HH:mm:ss"))
                .orderByDesc(Alarm::getAlarmTime));
    }
}

